<?php

declare(strict_types=1);

namespace app\controller\sys;

use think\facade\View;
use think\facade\Config;
use think\facade\Session;
use think\exception\ValidateException;

use app\model\SysUser as SysUserModel;
use app\model\SysRole as SysRoleModel;
use app\utils\ReUtils;


/**
 * +----------------------------------------------------------------------
 * | 管理员控制制器
 * +----------------------------------------------------------------------
 */
class SysUser extends Base
{
    protected $modelName = "SysUser";

    public function index()
    {
        $list = SysUserModel::queryList();

        View::assign('list', $list);

        return View::fetch();
    }

    // public function info($id = 0)
    // {
    //     if ($id != 0) {
    //         $data = $this->model->find($id);
    //     } else {
    //         $data = ['id'=>0, 'username' => '', 'role_id' => 0, 'truename' => '', 'email' => '', 'note' => ''];
    //     }

    //     $dataRole = SysRoleModel::column('name','id');

    //     return  View::fetch('save',[
    //         'data' => $data,
    //         'dataRole' => $dataRole
    //     ]);
    // }

    public function save($id = 0)
    {
        if ($this->app->request->isPost()) {
            $params = $this->app->request->param();
            if ($params['username'] == '' || $params['roleid'] == '') {
                $this->error("用户名 or 角色 不能为空!");
            }

            try {
                $id = $params['userid'];
                unset($params['userid']);

                if ($id != 0) {
                    if (empty($params['password'])) {
                        unset($params['password']);
                    } else {
                        $params['salt'] = generate_stochastic_string();
                        $params['password'] = md5($params['password'] . $params['salt']);
                    }
                    SysUserModel::update($params, ['userid' => $id]);
                } else {
                    $params['password'] = empty($params['password']) ? Config::get('app.default_password') : $params['password'];
                    $params['salt'] = generate_stochastic_string();
                    $params['password'] = md5($params['password'] . $params['salt']);
                    SysUserModel::create($params);
                }
            } catch (\Exception $e) {
                $msg = $e->getMessage();

                return ReUtils::error("错误代码:" . $msg);                
            }
            
            return ReUtils::success();
        } else {
            if ($id != 0) {
                $data = SysUserModel::find($id);
            } else {
                $data = new SysUserModel();
            }

            $dataRole = SysRoleModel::column('name', 'roleid');

            View::assign('data', $data);

            View::assign('dataRole', $dataRole);

            return  View::fetch();
        }
    }

    /**
     * 检测用户名是否可用
     * @param int $id 管理员userid
     * @param string $username 管理员用户名
     * @return Response
     */
    public function isAvailable($userid = null, $username = '')
    {
        if ($this->app->request->isAjax()) {
            $data = SysRoleModel::where('username', $username)->find();
            if ($data && $data->userid != $userid) {
                return ReUtils::error('用户名已存在, 请使用其他用户名');
            } else {
                return ReUtils::success('用户名可用');
            }
        }
    }

    /**
     * 删除
     * @param int $id 管理员userid
     * @return Response
     */
    public function delete($id = null)
    {
        if ($this->app->request->isAjax()) {
            if (is_array($id)) {
                if (in_array(session('uid'), $id)) {
                    return ReUtils::error('当前登录用户无法删除');
                }
            } else {
                if ($id == session('uid')) {
                    return ReUtils::error('当前登录用户无法删除');
                }
            }
            if (SysUserModel::destroy($id)) {
                return ReUtils::success();
            } else {
                return ReUtils::error();
            }
        }
    }

    /**
     * 头像上传
     */
    public function avatar()
    {
        if ($this->app->request->isPost()) {
            $avatar = $this->app->request->param('avatar');

            $info = SysUserModel::find(session('adminuser.userid'));

            $info->avatar = $avatar;

            if ($info->save()) {
                Session::set('adminuser.avatar', $avatar);
                
                return ReUtils::success();
            } else {
                return ReUtils::error();
            }
        } else {
            View::assign('avatar', Session::get('adminuser.avatar'));

            return View::fetch();
        }
    }

    // 修改密码
    public function password()
    {
        if ($this->app->request->isPost()) {
            $params = $this->app->request->param();

            $info = SysUserModel::field('password,salt')->find(session('adminuser.userid'));

            if ($info->password != md5($params['oldpassword'] . $info->salt)) {
                $this->error('原密码不正确');
            }

            if ($params['newpassword'] != $params['repassword']) {
                $this->error('两次新密码不一致，请核查');
            }

            $info->salt = generate_stochastic_string();
            $info->password = md5($params['newpassword'] . $info->salt);

            if ($info->save()) {
                session(null);
                $this->success("修改成功,请重新登陆", 'login/index');
            } else {
                $this->error('修改失败，请稍后重试');
            }
        } else {
            return View::fetch();
        }
    }
}
